package com.acmelabs.inbox;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import adhoc.tel.fer.hr.R;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class NotificationInbox extends ListActivity {

	private static final DateFormat dateFormatIn = new SimpleDateFormat(
			"MMMMMMMMM d, yyyy HH:mm:ss");
	private static final DateFormat dateFormatOut = new SimpleDateFormat(
			"MMMMMMMMM d, yyyy");
	ArrayList<Notification> nt = new ArrayList<Notification>();
	Notification selectedNotification;
	private Context mContext;
	ObjectInputStream ois;
	static final String FILE_NAME = "ACME_LABS";

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notification_inbox);
		mContext = this;
		registerForContextMenu(getListView());
		String extras = this.getIntent().getStringExtra("c");

		if (extras != null && extras.equals("CLEAR")) { 
			nt = new ArrayList<Notification>();
			NotificationIO io = new NotificationIO();
			FileOutputStream fos;
			try {
				fos = mContext.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
				io.write(nt, fos);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			noNotificationMsg();
		} else {
			loadNotification();
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(1, 1, 1, "Delete Alert");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		switch (item.getItemId()) {
		case 1: {
			int size = nt.size();
			int infopostion = info.position;
			int reversePostion = size - infopostion;
			reversePostion = reversePostion - 1;
			nt.remove(reversePostion);
			NotificationIO io = new NotificationIO();
			FileOutputStream fos;
			try {
				fos = mContext.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
				io.write(nt, fos);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			Intent intent = new Intent(NotificationInbox.this,
					NotificationInbox.class);
			startActivity(intent);
			this.finish();
			return true;
		}
		}
		return true;
	}

	private void loadNotification() {

		final List<NotificationItem> BigNotiItems = new ArrayList<NotificationItem>();
		if (refreshInbox()) {
			List<Notification> NotiEntries = nt;
			for (int i = NotiEntries.size() - 1; i >= 0; i--) {
				Notification NotifEntries = NotiEntries.get(i);
				NotificationItem notiItem = new NotificationItem();
				notiItem.title = Html.fromHtml(NotifEntries.getTitle())
						.toString();
				try {
					Date timestamp = dateFormatIn.parse(NotifEntries
							.getDateAndTime());
					notiItem.time = dateFormatOut.format(timestamp);
				} catch (ParseException e) {
				}
				notiItem.details = getDescriptionTrim(NotifEntries.getDetails()
						.replaceAll("\\<[^>]*>", ""));	
				try {
					BigNotiItems.add(notiItem);
					NotificationListAdapter flareAdapter = new NotificationListAdapter(
							LayoutInflater.from(mContext), BigNotiItems);
					setListAdapter(flareAdapter);
					getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
					getListView().setCacheColorHint(Color.TRANSPARENT);
					getListView().setTextFilterEnabled(false);

				} catch (Exception e) {
					noNotificationMsg();
				}
			}
		} else {
			noNotificationMsg();
		}

	}

	void noNotificationMsg() {
		TextView emptyListMessage = (TextView) findViewById(R.id.emptyListMessage);
		emptyListMessage.setText("Notification Inbox Empty");
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		int size = nt.size();
		int infopostion = position;
		int reversePostion = size - infopostion;
		reversePostion = reversePostion - 1;
		selectedNotification = nt.get(reversePostion);

		Intent intent = new Intent("com.xtify.android.sdk.NOTIFICATION_CLICKED");

		intent.putExtra("NOTIFICATION_TITLE", selectedNotification.getTitle());
		intent.putExtra("NOTIFICATION_DETAILS", selectedNotification
				.getDetails());
		intent.putExtra("NOTIFICATION_URL", selectedNotification.getUrl());
		intent.putExtra("NOTIFICATION_CP_ID", selectedNotification.getID());
		intent
				.putExtra("NOTIFICATION_TICKER", selectedNotification
						.getTicker());
		intent.putExtra("NOTIFICATION_ACTION_COMPONENT", selectedNotification
				.getActionComponent());
		intent.putExtra("NOTIFICATION_ACTION_LABEL", selectedNotification
				.getActionLable());
		intent.putExtra("NOTIFICATION_ACTION_NAME", selectedNotification
				.getActionName());
		intent.putExtra("NOTIFICATION_ACTION_CATEGORIES", selectedNotification
				.getActionCategories());
		intent.putExtra("NOTIFICATION_ACTION_DATA", selectedNotification
				.getActionData());
		intent.putExtra("NOTIFICATION_SHOW_THUMBS", selectedNotification
				.isShowThumbs());
		intent.putExtra("NOTIFICATION_LOCATION_LATITUDE", selectedNotification
				.getLocationLatitude());
		intent.putExtra("NOTIFICATION_LOCATION_LONGITUDE", selectedNotification
				.getLocationLongitude());

		intent.setData(Uri.parse("notif://notification.xtify.com/"
				+ selectedNotification.getID() + "/"
				+ System.currentTimeMillis()));
		sendBroadcast(intent);
	}

	Boolean refreshInbox() {
		try {
			NotificationIO io = new NotificationIO();
			if (io.read(mContext)) {
				nt = io.getNotificationList();
				if (nt.size() == 0) {
					return false;
				}
				return true;
			} else {
				return false;
			}

		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, 0, 0, "Clear");
		menu.findItem(0).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0: {
			Intent intent = new Intent(NotificationInbox.this,
					NotificationInbox.class);
			intent.putExtra("c", "CLEAR");
			startActivity(intent);
			this.finish();
			return true;
		}
		}
		return false;
	}

	private String getDescriptionTrim(String description) {
		String result;
		result = description;
		if (result.length() > 128) {
			result = result.substring(0, 125) + "...";
		}
		return result;
	}
}
